package com.hfjyz.registration.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.hfjyz.registration.command.AdminLoginCommand;
import com.hfjyz.registration.command.AnnouncementEditCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.service.AnnouncementService;

public class AnnouncementEditController extends SimpleFormController {

	private AnnouncementService announcementService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.mvc.AbstractWizardFormController#
	 * referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object,
	 * org.springframework.validation.Errors, int)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		AnnouncementEditCommand cmd = (AnnouncementEditCommand) command;
		String id = request.getParameter("id");
		if (id != null && id.length() > 0) {
			try {
				cmd.setId(Integer.valueOf(id));
			} catch (Exception e) {
			}
		}
		return announcementService.initEdit(cmd, errors);
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		AnnouncementEditCommand cmd = (AnnouncementEditCommand) command;
		AdminLoginCommand adminCmd = (AdminLoginCommand) request.getSession()
				.getAttribute("AdminInfo");
		if (cmd.getId() == null) {
			announcementService.loggin(request, ExamContants.LOGING_TYPE_INFO,
					(Integer) null, ExamContants.LOGING_USER_TYPE_MANAGE,
					adminCmd.getAdminId(), ExamContants.LOGING_OP_TYPE_ADD,
					"公告追加");
		} else {
			announcementService.loggin(request, ExamContants.LOGING_TYPE_INFO,
					(Integer) null, ExamContants.LOGING_USER_TYPE_MANAGE,
					adminCmd.getAdminId(), ExamContants.LOGING_OP_TYPE_EDIT,
					"公告编辑");
		}
		announcementService.editOk(request, cmd, errors);
		if (errors.hasErrors()) {
			return new ModelAndView(getFormView(), errors.getModel());
		}
		return new ModelAndView(new RedirectView("announcementList.action"),
				errors.getModel());
	}

	public AnnouncementService getAnnouncementService() {
		return announcementService;
	}

	public void setAnnouncementService(AnnouncementService roomService) {
		this.announcementService = roomService;
	}

}